<template>
    <div class="hotspot-container">
        <div class="hotspot-list-container">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-state">
                <el-icon class="loading-icon"><Refresh /></el-icon>
                <span>正在从智能体加载热点数据...</span>
            </div>

            <!-- 错误提示 -->
            <div v-else-if="errorMessage" class="error-state">
                <el-icon class="error-icon"><Warning /></el-icon>
                <div class="error-content">
                    <div class="error-title">数据加载失败</div>
                    <div class="error-message">{{ errorMessage }}</div>
                    <el-button type="primary" @click="loadHotspots" class="retry-btn">
                        <el-icon><Refresh /></el-icon>
                        重新加载
                    </el-button>
                </div>
            </div>

            <!-- 无数据状态 -->
            <div v-else-if="filteredHotspots.length === 0" class="empty-state">
                <el-icon class="empty-icon"><Document /></el-icon>
                <div class="empty-content">
                    <div class="empty-title">暂无热点数据</div>
                    <div class="empty-message">请确保后端智能体服务已启动</div>
                    <el-button type="primary" @click="loadHotspots" class="refresh-btn">
                        <el-icon><Refresh /></el-icon>
                        刷新数据
                    </el-button>
                </div>
            </div>

            <!-- 热点列表 -->
            <div v-else class="hotspot-list">
                <!-- 标签页和刷新按钮 -->
                <div class="refresh-header">
                    <div class="header-left">
                        <!-- 平台标签页 -->
                        <div class="platform-tabs">
                            <el-button 
                                :class="['platform-tab', { 'active': activePlatform === 'all' }]"
                                @click="activePlatform = 'all'"
                                text
                            >
                                全部
                            </el-button>
                            <el-button 
                                :class="['platform-tab', { 'active': activePlatform === 'weibo' }]"
                                @click="activePlatform = 'weibo'"
                                text
                            >
                                <img :src="getSourceIcon('微博')" class="hotspot-icon" alt="微博">
                                微博热搜
                            </el-button>
                            <el-button 
                                :class="['platform-tab', { 'active': activePlatform === 'toutiao' }]"
                                @click="activePlatform = 'toutiao'"
                                text
                            >
                                <img :src="getSourceIcon('头条')" class="hotspot-icon" alt="头条">
                                头条热搜
                            </el-button>
                            <el-button 
                                :class="['platform-tab', { 'active': activePlatform === 'douyin' }]"
                                @click="activePlatform = 'douyin'"
                                text
                            >
                                <img :src="getSourceIcon('抖音')" class="hotspot-icon" alt="抖音">
                                抖音热搜
                            </el-button>
                        </div>
                    </div>
                    <div class="header-right">
                        <div class="button-group">
                            <el-button @click="refreshData" type="primary" text>
                                <el-icon><Refresh /></el-icon>
                                刷新数据
                            </el-button>
                            <el-button @click="fetchNow" type="success" text>
                                <el-icon><Download /></el-icon>
                                立即获取
                            </el-button>
                        </div>
                    </div>
                </div>
                

                <div class="hotspot-item" v-for="hotspot in filteredHotspots" :key="`${hotspot.platform}-${hotspot.index}`">
                    <div class="hotspot-header">
                        <div class="hotspot-rank">
                            <span class="rank-number">{{ hotspot.index }}</span>
                            <h4 class="hotspot-title">{{ hotspot.title }}</h4>
                        </div>
                        <div class="card-actions">
                            <el-button type="primary" @click="openGenerate(hotspot)">
                                <el-icon class="mr-1">
                                    <Edit />
                                </el-icon>
                                一键生成
                            </el-button>
                        </div>
                    </div>

                    <div class="hotspot-meta">
                        <span class="meta-item">
                            <img :src="getSourceIcon(hotspot.platform)" class="hotspot-icon" alt="来源">
                            {{ hotspot.platform }}
                        </span>
                        <span class="meta-item">
                            <img :src="getStatsIcon(hotspot.hot)" class="hotspot-icon" alt="热度">
                            {{ formatHotValue(hotspot.hot) }}
                        </span>
                        <span class="meta-item">
                            <a :href="hotspot.url" target="_blank" class="hotspot-link">查看详情</a>
                        </span>
                    </div>

                    <p class="hotspot-content" v-if="hotspot.summary">{{ hotspot.summary }}</p>
                    <p class="hotspot-content no-summary" v-else>暂无事件总结</p>

                    <div class="hotspot-tags">
                        <span class="tag-item platform-tag">{{ hotspot.platform }}</span>
                        <span class="tag-item hot-tag">热度: {{ formatHotValue(hotspot.hot) }}</span>
                    </div>
                </div>
            </div>

            <el-dialog v-model="dialogVisible" :show-close="true" title="生成内容设置" :title-class="'dialog-title-bold'">
                <div class="dialog-body">
                    <!-- 操作说明 -->
                    <div class="label-title">
                        为以下热点选题生成适配多平台的内容，请选择发布平台和内容风格：
                    </div>
                    <el-input v-model="form.title" class="form-title-bold" :autosize="{ minRows: 2, maxRows: 4 }" />

                    <div class="platforms">
                        <div class="platform-item" :class="{ active: form.platforms.wechat }">
                            <div class="left">
                                <el-checkbox v-model="form.platforms.wechat" />
                            </div>
                            <div class="right">
                                <div class="name">
                                    <img :src="getSourceIcon('微信公众号')" class="hotspot-icon" alt="平台">
                                    微信公众号
                                </div>
                                <div class="desc">图文消息、公众号文章</div>
                            </div>
                        </div>
                        <div class="platform-item" :class="{ active: form.platforms.weibo }">
                            <div class="left">
                                <el-checkbox v-model="form.platforms.weibo" />
                            </div>
                            <div class="right">
                                <div class="name">
                                    <img :src="getSourceIcon('微博')" class="hotspot-icon" alt="平台">
                                    微博
                                </div>
                                <div class="desc">微博博文、话题互动</div>
                            </div>
                        </div>
                        <div class="platform-item" :class="{ active: form.platforms.douyin }">
                            <div class="left">
                                <el-checkbox v-model="form.platforms.douyin" />
                            </div>
                            <div class="right">
                                <div class="name"><img :src="getSourceIcon('抖音')" class="hotspot-icon" alt="平台">
                                    抖音</div>
                                <div class="desc">短视频脚本、文案、话题标签</div>
                            </div>
                        </div>
                    </div>
                    <div class="style-settings">
                        <div class="label">内容风格</div>
                        <div class="style-tags">
                            <el-check-tag v-for="style in styles" :key="style" :checked="form.styles.includes(style)"
                                @change="toggleStyle(style)">
                                {{ style }}
                            </el-check-tag>
                        </div>
                    </div>
                </div>
                <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmGenerate">确认生成</el-button>
                </template>
            </el-dialog>
        </div>


        <div class="right-container">
            <!-- 数据卡片区域 -->
            <div class="data-cards-column">
                <DataCard icon-src="/热门.svg"   label="今日热点数"
                    :value="dataStats.todayHotspots" />
                <DataCard icon-src="/用户.svg"  label="覆盖用户量"
                    :value="dataStats.userCoverage" />
            </div>


            <!-- 词云区域 -->
            <div class="wordcloud-container">
                <div class="wordcloud-header">
                    <div class="title-section">
                        <h3 class="wordcloud-title">实时热词监控</h3>
                        <div class="live-indicator">
                            <span class="live-dot"></span>
                            <span class="live-text">实时同步中</span>
                        </div>
                    </div>
                </div>
                <div class="wordcloud-chart">
                    <!-- 加载状态 -->
                    <div v-if="trendDataLoading" class="wordcloud-loading">
                        <el-icon class="loading-icon"><Refresh /></el-icon>
                        <span>加载词云数据中...</span>
                    </div>
                    
                    <!-- 错误状态 -->
                    <div v-else-if="trendDataError" class="wordcloud-error">
                        <el-icon class="error-icon"><Warning /></el-icon>
                        <span>{{ trendDataError }}</span>
                    </div>
                    
                    <!-- 无数据状态 -->
                    <div v-else-if="data.length === 0" class="wordcloud-empty">
                        <el-icon class="empty-icon"><Document /></el-icon>
                        <span>暂无词云数据</span>
                    </div>
                    
                    <!-- 正常状态 -->
                    <WordCloudMap v-else :data="data" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
import { getSourceIcon, getStatsIcon } from '../utils/iconMaps';
import { Edit, Refresh, Warning, Document, Download } from '@element-plus/icons-vue'
import WordCloudMap from './WordCloudMap.vue'
import DataCard from './DataCard.vue'
import apiService from '../services/apiService'

// 初始化空数组，不使用静态默认数据
const data = ref([]);
const trendDataLoading = ref(false);
const trendDataError = ref('');

const router = useRouter()
const dialogVisible = ref(false)
const form = ref({
    title: '',
    platforms: { wechat: false, weibo: false, douyin: false },
    styles: ['专业严谨']
})
const styles = ['专业严谨', '轻松活泼', '深度分析', '幽默风趣', '客观中立']
const hotspots = ref([])
const classifiedData = ref({})
const loading = ref(false)
const errorMessage = ref('')
const dataStats = ref({
    todayHotspots: '0',
    userCoverage: '0'
})
const activePlatform = ref('all')

// 计算属性：过滤后的热点数据
const filteredHotspots = computed(() => {
    if (activePlatform.value === 'all') {
        // 合并所有平台的数据
        const allHotspots = []
        if (classifiedData.value.weibo) {
            classifiedData.value.weibo.data.forEach(item => {
                allHotspots.push({ ...item, platform: '微博' })
            })
        }
        if (classifiedData.value.toutiao) {
            classifiedData.value.toutiao.data.forEach(item => {
                allHotspots.push({ ...item, platform: '头条' })
            })
        }
        if (classifiedData.value.douyin) {
            classifiedData.value.douyin.data.forEach(item => {
                allHotspots.push({ ...item, platform: '抖音' })
            })
        }
        return allHotspots.sort((a, b) => a.index - b.index)
    } else {
        // 返回特定平台的数据
        const platformData = classifiedData.value[activePlatform.value]
        return platformData ? platformData.data.map(item => ({ ...item, platform: platformData.platform })) : []
    }
})

// 计算属性：平台统计数据
const platformStats = computed(() => {
    return {
        weibo: classifiedData.value.weibo ? classifiedData.value.weibo.count : 0,
        toutiao: classifiedData.value.toutiao ? classifiedData.value.toutiao.count : 0,
        douyin: classifiedData.value.douyin ? classifiedData.value.douyin.count : 0
    }
})

// 加载趋势分析数据
const loadTrendData = async () => {
  trendDataLoading.value = true;
  trendDataError.value = '';
  
  try {
    console.log('开始加载词云数据...');
    
    // 加载词云数据
    const wordCloudResult = await apiService.getWordCloud();
    console.log('词云API响应:', wordCloudResult);
    
    if (wordCloudResult.success && wordCloudResult.data) {
      console.log('成功获取词云数据，数量:', wordCloudResult.data.length);
      // 只保留有效数据（名称和权重都存在）
      data.value = wordCloudResult.data.filter(item => 
        item.name && typeof item.name === 'string' && 
        item.value && typeof item.value === 'number' && 
        item.value > 0
      );
      console.log('过滤后的词云数据数量:', data.value.length);
    } else {
      console.warn('词云API返回数据无效或为空');
      data.value = [];
    }

    // 加载统计数据
    const statsResult = await apiService.getTrendStats();
    console.log('统计API响应:', statsResult);
    
    if (statsResult.success && statsResult.data) {
      const { today_stats, user_coverage_trend } = statsResult.data;
      if (today_stats) {
        dataStats.value.todayHotspots = today_stats.today_hotspots || 
                                       today_stats.hotspots_count || '0';
      }
      if (user_coverage_trend) {
        dataStats.value.userCoverage = user_coverage_trend.current_coverage || 
                                      user_coverage_trend.user_coverage || '0';
      }
    }
  } catch (error) {
    console.error('获取趋势数据失败:', error);
    trendDataError.value = '获取词云数据失败';
    // 发生错误时不显示默认的无关词，保持为空数组
    data.value = [];
  } finally {
    trendDataLoading.value = false;
  }
}

// 从后端API加载热点数据 - 使用统一的API服务
const loadHotspots = async () => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const result = await apiService.getHotspots()
    
    if (result.success && result.data) {
      // 假设后端返回的数据已经是分类好的结构
      classifiedData.value = result.data
      // 更新统计数据 - 计算总热点数
      const totalCount = Object.values(classifiedData.value).reduce((sum, platformData) => {
        return sum + (platformData.count || 0)
      }, 0)
      dataStats.value.todayHotspots = totalCount.toString()
      dataStats.value.userCoverage = Math.floor(totalCount * 2.5) + '万'
    } else {
      // 后端服务正常但无数据
      classifiedData.value = {}
      errorMessage.value = result.message || '暂无热点数据，请稍后重试'
    }
  } catch (error) {
    console.error('获取热点数据失败:', error)
    classifiedData.value = {}
    errorMessage.value = '后端服务未启动，请启动后端服务后刷新页面'
  } finally {
    loading.value = false
  }
}

// 手动刷新数据
const refreshData = async () => {
  try {
    // 使用统一的API服务
    await apiService.refreshData()
    // 然后重新加载数据
    await Promise.all([
      loadHotspots(),
      loadTrendData()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  }
}

// 立即获取最新微博数据
const fetchNow = async () => {
  try {
    const result = await apiService.fetchNow()
    
    if (result.success) {
      ElMessage.success(result.message)
      // 等待2秒后重新加载数据
      setTimeout(() => {
        loadHotspots()
        loadTrendData()
      }, 2000)
    } else {
      ElMessage.warning(result.message)
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadHotspots()
  loadTrendData()
})

// 打开生成对话框
const openGenerate = (hotspot) => {
    form.value.title = hotspot?.title || ''
    dialogVisible.value = true
}

// 切换风格标签
const toggleStyle = (style) => {
    const set = new Set(form.value.styles)
    if (set.has(style)) set.delete(style)
    else set.add(style)
    form.value.styles = Array.from(set)
}

// 格式化热度值 - 统一显示格式
const formatHotValue = (hotValue) => {
    if (hotValue === null || hotValue === undefined) {
        return '未知'
    }

    // 处理字符串类型的万单位热度值（如"108.8万"）
    if (typeof hotValue === 'string' && hotValue.includes('万')) {
        // 直接返回，保持万单位显示
        return hotValue
    }

    // 处理数字类型的热度值
    if (typeof hotValue === 'number') {
        if (hotValue >= 100000000) {
            return (hotValue / 100000000).toFixed(1) + '亿'
        } else if (hotValue >= 10000) {
            return (hotValue / 10000).toFixed(1) + '万'
        } else if (hotValue >= 1000) {
            return (hotValue / 1000).toFixed(1) + '千'
        }
        return hotValue.toString()
    }

    // 其他情况直接返回
    return hotValue || '未知'
}

// 确认生成内容时使用路由跳转
const confirmGenerate = () => {
    // 检查是否至少勾选了一个平台
    const hasSelectedPlatform = Object.values(form.value.platforms).some(Boolean)
    if (!hasSelectedPlatform) {
        ElMessage.warning('请至少勾选一个发布平台')
        return
    }
    
    dialogVisible.value = false
    try {
        localStorage.setItem('selectedPlatforms', JSON.stringify(form.value.platforms))
    } catch (error) {
        console.warn('无法访问localStorage:', error)
    }
    router.push({
        path: '/creation',
        query: { title: encodeURIComponent(form.value.title) }
    })
}

</script>

<style scoped>
/* 样式保持不变 */
.hotspot-container {
    display: flex;
    gap: 24px;
    height: 100%;
}

.hotspot-list-container {
    flex: 1;
    max-width: 80%;
}

.right-container {
    flex: 1;
    max-width: 20%;
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-right: 10px;
}

.data-cards-column {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.wordcloud-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 0;
    overflow: hidden;
    transition: all 0.3s ease;
}

.wordcloud-container:hover {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* 词云状态样式 */
.wordcloud-chart {
    position: relative;
    width: 100%;
    height: 400px;
    min-width: 400px;
}

.wordcloud-loading,
.wordcloud-error,
.wordcloud-empty {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #606266;
    font-size: 14px;
    gap: 12px;
}

.wordcloud-loading .loading-icon {
    font-size: 32px;
    color: #409EFF;
    animation: rotate 2s linear infinite;
}

.wordcloud-error .error-icon {
    font-size: 32px;
    color: #F56C6C;
}

.wordcloud-empty .empty-icon {
    font-size: 32px;
    color: #909399;
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* 词云头部样式 */
.title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    margin-left: 20px;
    margin-right: 10px;
}

.wordcloud-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
}

.live-indicator {
    display: flex;
    align-items: center;
    gap: 6px;
    background: #ecfdf5;
    padding: 4px 8px;
    border-radius: 12px;
    border: 1px solid #d1fae5;
}

.live-dot {
    width: 6px;
    height: 6px;
    background: #10b981;
    border-radius: 50%;
    animation: pulse 2s infinite;
}

.live-text {
    font-size: 12px;
    font-weight: 500;
    color: #065f46;
}

.wordcloud-chart {
    padding: 20px;
    height: 340px; 
    min-height: 340px; 
    display: flex;
    align-items: center;
    justify-content: center;
}

@keyframes pulse {
    0%, 100% {
        opacity: 1;
    }
    50% {
        opacity: 0.5;
    }
}
</style>
